package com.qzdsoft.erpcloud.service.sys.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.qzdsoft.erpcloud.domain.sys.SysMenuButton;
import com.qzdsoft.erpcloud.domain.sys.User;
import com.qzdsoft.erpcloud.mapper.sys.MenuButtonQueryMapper;
import com.qzdsoft.erpcloud.mapper.sys.SysMenuButtonMapper;
import com.qzdsoft.erpcloud.service.sys.RedisService;
import com.qzdsoft.erpcloud.service.sys.SysMenuButtonService;
import com.qzdsoft.erpcloud.vo.stock.StockInboundInfo;
import com.qzdsoft.erpcloud.vo.sys.MenuInfo;
import com.qzdsoft.erpcloud.vo.sys.SysMenubuttonQueryInfo;
import com.qzdsoft.erpcloud.vo.sys.SysMenubuttonQueryParam;
import com.qzdsoft.erpcloud.vo.sys.ZtreeNode;
import com.qzdsoft.utils.StringUtil;
import com.qzdsoft.vo.LayTableResponse;
import com.qzdsoft.vo.Page;
import com.qzdsoft.vo.PageRequest;
import com.qzdsoft.vo.Response;
import com.qzdsoft.vo.ResultEnum;
import com.qzdsoft.vo.TypeInfo;
import com.qzdsoft.vo.sys.SysMenuButtonTypeEnum;

@Service
public class SysMenuButtonServiceImpl implements SysMenuButtonService {
    private final static Logger logger = LoggerFactory.getLogger(SysMenuButtonServiceImpl.class);
    @Autowired
    private SysMenuButtonMapper menuMapper;
    
    @Autowired
    private MenuButtonQueryMapper menuButtonQueryMapper;
    
   
    
//    @Autowired
//    private RedisTask redisTask;

//    @Override
//    public Integer selectDataCount(String name,String url) {
//        return menuMapper.selectDataCount(name,url);
//    }
//
//    @Override
//    public List<Map<String, Object>> selectData(String name,String url, Integer start, Integer pageSize) {
//        return menuMapper.selectData(name,url, start, pageSize);
//    }

    @Override
    public Response edit(SysMenuButton sysMenuButton) {
        if(sysMenuButton.getType()== SysMenuButtonTypeEnum.functionMenu.getKey() && sysMenuButton.getUrl().equals("")){
            return Response.success("功能菜单的url不能为空");
        }
        if(!StringUtil.isEmpty(sysMenuButton.getId()) ){        //  编辑
//            if(!checkSortAvailable(sysMenuButton.getSort(),sysMenuButton.getSuper_id(),sysMenuButton.getId())){
//                return Response.error("当前排序数已被使用");
//            }
            int ui = menuMapper.updateByPrimaryKey(sysMenuButton);
            return Response.success("编辑成功");
        } else {
//            if(!checkSortAvailable(sysMenuButton.getSort(),sysMenuButton.getSuper_id(),null)){
//                return Response.error("当前排序数已被使用");
//            }
            sysMenuButton.setCtime(new Date());
            logger.debug("菜单新增前主键id={}",sysMenuButton.getId());
            menuMapper.insert(sysMenuButton);
            logger.debug("菜单新增后主键id={}",sysMenuButton.getId());
            return Response.success("新增成功");
        }
    }

    @Override
    public Response del(Integer id) {
        menuMapper.deleteByPrimaryKey(id);
        return Response.success("删除数据成功");
    }

    @Override
    public Page<SysMenuButton> findPage(SysMenubuttonQueryParam params, User user) {
        PageRequest request = new PageRequest(params.getiDisplayStart()/params.getiDisplayLength()+1, params.getiDisplayLength());
        Integer companyId=null;
        companyId = user.getCompanyId();
        long count = menuMapper.countMenu(params.getName());
        if (count == 0) {
            return new Page<SysMenuButton>(new ArrayList<SysMenuButton>(), count,params.getsEcho(),request);
        }

        List<SysMenuButton> result = menuMapper.findPageMenu(request,params.getName());
        Page<SysMenuButton> menus = new Page<>(result, count,params.getsEcho(),request);
        if (menus.getCurrentPage() > menus.getTotalPage()) {
            request = new PageRequest(menus.getTotalPage(), params.getiDisplayLength());
            result = menuMapper.findPageMenu(request,params.getName());
            menus = new Page<>( result, count,params.getsEcho(),request);
        }
        return menus;
    }

    @Override
    public SysMenuButton selectById(Integer menuId) {
        return menuMapper.selectByPrimaryKey(menuId);
    }

//    @Override
//    public Response addMenu(Integer superId,String name,String url,Short status,Integer type,String remarks,Integer sort) {
//        if(!checkSortAvailable(sort,superId,null)){
//            return Response.error("当前排序数已被使用");
//        }
//        SysMenuButton menu = new SysMenuButton();
//        menu.setSuper_id(superId==null?-1:superId);
//        menu.setName(name);
//        menu.setUrl(url);
//        menu.setStatus(status);
//        menu.setType(type);
//        menu.setRemark(remarks);
//        menu.setSort(sort);
//        menu.setCtime(new Date());
//        menuMapper.insert(menu);
//        //更新redis
////        redisTask.sysMenuButton();
//        return new Response(ResultEnum.SUCCESS.getCode(),"新增菜单成功",menu);
//    }

    /**
     * 检查排序数是否可用
     * @param sort 排序数
     * @param id id为空时新增排序，编辑排序
     * @return
     */
    public boolean checkSortAvailable(Integer sort,Integer superId,Integer id){
        List<SysMenuButton> list = menuMapper.getBySort(sort,superId);
        if(null==id){
            return !(null != list && list.size() > 0);
        }else{
            if(null==list || list.size()==0){
                return true;
            }else{
                if(list.size()>1){
                    return false;
                }else{
                    return list.get(0).getId().equals(id);
                }
            }
        }
    }

//    @Override
//    public Response editMenu(Integer superId,String name,String url,Short status,Integer type,String remarks,Integer sort,Integer menuId) {
//        if(!checkSortAvailable(sort,superId,menuId)){
//            return Response.error("当前排序数已被使用");
//        }
//        SysMenuButton menu = selectById(menuId);
//        menu.setSuper_id(superId==null?-1:superId);
//        menu.setName(name);
//        menu.setUrl(url);
//        menu.setStatus(status);
//        menu.setType(type);
//        menu.setRemark(remarks);
//        menu.setSort(sort);
//        menuMapper.updateByPrimaryKey(menu);
//        //更新redis
////        redisTask.sysMenuButton();
//        return new Response(ResultEnum.SUCCESS.getCode(),"编辑菜单成功",menu);
//    }

    @Override
    public List<SysMenuButton> getAllTopMenu() {
        return menuMapper.getAllTopMenu();
    }

    @Override
    public List<SysMenuButton> selectAll(Integer status, Integer type) {
        return menuMapper.selectAll(status, type);
    }

    @Override
    public List<SysMenuButton> selectAllByRoleId(Integer status, Integer type, Integer roleId) {
        return menuMapper.selectAllByRoleId(status, type, roleId);
    }

    @Override
    public Response delteMenu(Integer menuId) {
        return new Response(ResultEnum.SUCCESS.getCode(),"删除菜单成功",menuMapper.deleteByPrimaryKey(menuId));
    }

    @Override
    public List<MenuInfo> selectAuthorizeMenu(Integer uid)
    {
        Integer hasAllAuthorized = menuButtonQueryMapper.isHasAllFunction(uid);
        List<MenuInfo> menus = new ArrayList<>();
        //如果具有所有权限查询所有菜单
        if(hasAllAuthorized==1) {
            menus  = menuButtonQueryMapper.queryAllMenu();
        }else {
            menus = menuButtonQueryMapper.queryAuthorizedMenu(uid);
        }
        
        List<MenuInfo> menuInfos = new ArrayList<>();
        for(int i=0;i<menus.size();i++) {
            MenuInfo menu = menus.get(i);
            //获取所有根节点的菜单
            if(menu.getSupperid()==-1) {
                menuInfos.add(menu);
                menus.remove(i);
                i--;
                getChildrenMenus(menu,menus);
            }
        }
        
        return menuInfos;
    }
    private void getChildrenMenus(MenuInfo parent,List<MenuInfo> menus) {
        for(int i=0;i<menus.size();i++) {
            MenuInfo menu = menus.get(i);
            if(menu.getSupperid().equals(parent.getId())) {
                parent.getChildrens().add(menu);
                menus.remove(i);
                i--;
                getChildrenMenus(menu, menus);
            }
        }
    }

    @Override
    public List<TypeInfo> selectAuthorizedButton(Integer uid)
    {
        Integer hasAllAuthorized = menuButtonQueryMapper.isHasAllFunction(uid);
        if(hasAllAuthorized==1) {
            return menuButtonQueryMapper.selectAllButton();
        }else {
            return menuButtonQueryMapper.selectAuthorizedButton(uid);
        }
    }

    @Override
    public List<String> selectAuthorizedUrl(Integer uid)
    {
        Integer hasAllAuthorized = menuButtonQueryMapper.isHasAllFunction(uid);
        if(hasAllAuthorized==1) {
            return menuButtonQueryMapper.selectAllUrl();
        }else {
            return menuButtonQueryMapper.selectAuthorizedUrl(uid);
        }
    }

	@Override
	public LayTableResponse<SysMenuButton> findAllData(SysMenubuttonQueryInfo info) {
		PageHelper.startPage(info.getPage(), info.getLimit());
		List<SysMenuButton> lists = menuButtonQueryMapper.findAllData(info);
		LayTableResponse<SysMenuButton> result = new LayTableResponse<SysMenuButton>(lists);
		return result;
	}

	@Override
	public List<ZtreeNode> selectAllMenu(Integer type) {
		List<ZtreeNode> lists = menuButtonQueryMapper.findMenuForZtree(type);
//		for(ZtreeNode list:lists) {
//			if(list.getpId() == -1) {
//				list.setOpen("true");
//			}
//		}
		return lists;
	}

	@Override
	public List<ZtreeNode> findByRoleId(Integer roleid,Integer uid) {
		// TODO Auto-generated method stub
		 Integer hasAllAuthorized = menuButtonQueryMapper.isHasAllFunction(uid);
		 if(hasAllAuthorized == 1) {//查所有的
			 return menuButtonQueryMapper.findByRoleId(roleid);
		 }else{
			 
			 return menuButtonQueryMapper.findByRoleUId(roleid,uid);
		 }
	}
    
	
}
